<template>
  <view class="store_detail_page">
    <u-navbar autoBack fixed placeholder bgColor="#f3f3f3">
      <template #left>
        <view class="navBar">
          <u-icon name="arrow-left" color="#000" size="18"></u-icon>
          <text class="nav_title">编写投诉</text>
        </view>
      </template>
    </u-navbar>
    <scroll-view scroll-y class="content" :style="{ height: `calc(100% - ${navBarHeight}px - 64rpx)` }">
      <view class="card_list">
        <u-form :model="form" :rules="rules" :labelWidth="90" ref="form">
          <view class="card_box">
            <u-form-item
              label="投诉类型"
              prop="complainType.dictLabel"
              @click="showComplainType = true"
            >
              <u--input
                v-model="form.complainType.dictLabel"
                Color="#ffffff"
                placeholder="请选择"
                border="none"
                readonly
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item
                label="事发地点"
                prop="address"
                @click="openMap"
            >
              <u--input
                  v-model="form.address"
                  Color="#ffffff"
                  placeholder="请选择"
                  border="none"
                  readonly
              ></u--input>
              <u-icon
                  slot="right"
                  name="arrow-right"
              ></u-icon>
            </u-form-item>
            <u-form-item
                label="投诉对象"
                prop="complainFor"
                borderBottom
            >
              <u--input
                  v-model="form.complainFor"
                  Color="#ffffff"
                  placeholder="请输入"
                  border="none"
              ></u--input>
            </u-form-item>
            <u-picker :show="showComplainType" :columns="complainTypeList" key-name="dictLabel" @confirm="confirmComplainType" @cancel="showComplainType = false"></u-picker>
            <u-form-item
                label-position="top"
                label="投诉原因"
                prop="complainReason"
                borderBottom
            >
              <view style="margin-top: 12px">
                <u-textarea v-model="form.complainReason" :maxlength="-1" :height="140" border="none" placeholder="请填写详细描述以便我们提供更好的帮助" />
              </view>
            </u-form-item>
            <u-form-item prop="imageList" label="上传图片" label-position="top">
              <view style="margin-top: 12px">
                <view style="margin-bottom: 50px;">
                  <u-upload
                      :fileList="form.imageList"
                      @afterRead="addImage"
                      @delete="deleteImage"
                      name="1"
                      :maxCount="1"
                      width="48"
                      height="48"
                  ></u-upload>
                </view>
              </view>
            </u-form-item>
          </view>
          <view class="card_box">
            <u-form-item
                label="联系人"
                prop="complainName"
                borderBottom
            >
              <u--input
                  v-model="form.complainName"
                  Color="#ffffff"
                  placeholder="请输入"
                  border="none"
              ></u--input>
            </u-form-item>
            <u-form-item
                label="联系电话"
                prop="complainPhone"
                borderBottom
            >
              <u--input
                  v-model="form.complainPhone"
                  Color="#ffffff"
                  placeholder="请输入"
                  border="none"
              ></u--input>
            </u-form-item>
          </view>
        </u-form>
      </view>
    </scroll-view>
    <view class="footer">
      <u-button type="primary" shape="circle" text="发 布" color="#0E9489" @click="next"></u-button>
    </view>
  </view>
</template>

<script>
import {getSystemDictTypeData} from "@/api/system";
import {uploadImg} from "@/api/home";
import {complainAdd} from "@/api/complaints";


const scope = 'scope.userLocation'
export default {
  async onLoad() {
    await this.getComplainTypeList()
    this.isGetLocation()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  data() {
    return {
      form: {
        // 投诉类型
        complainType: {},
        // 事发地点
        address: '',
        // 投诉对象
        complainFor: '',
        // 图片
        imageList: [],
        // 投诉原因
        complainReason: '',
        // 联系人
        complainName: '',
        // 联系电话
        complainPhone: ''
      },
      showComplainType: false,
      complainTypeList: [[]],
      // 地图位置
      latitude: 39.909,// 默认纬度
      longitude: 116.39742,// 默认经度(北京天安门)
      rules: {
        'complainType.dictLabel': {
          type: 'string',
          required: true,
          message: '请选择投诉类型',
          trigger: ['blur', 'change']
        },
        address: {
          type: 'string',
          required: true,
          message: '请选择事发地址',
          trigger: ['blur', 'change']
        },
        complainFor: {
          type: 'string',
          required: true,
          message: '请输入投诉对象',
          trigger: ['blur', 'change']
        },
        complainReason: {
          type: 'string',
          required: true,
          message: '请输入投诉原因',
          trigger: ['blur', 'change']
        },
        imageList: {
          type: 'array',
          validator: (rule, value, callback) => {
            console.warn(value, '2222222222')
            return this.form.imageList.length > 0 && this.form.imageList[0].status === 'success'
          },
          message: '请上传照片',
          trigger: ['blur', 'change']
        },
        complainName: {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        },
        complainPhone: [
          {
            type: 'string',
            required: true,
            message: '请输入联系方式',
            trigger: ['blur', 'change']
          },
          {
            // 自定义验证函数
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            trigger: ['change','blur'],
          }
        ]
      }
    }
  },
  computed: {
    navBarHeight () {
      const platform = uni.getSystemInfoSync().platform
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
      let navHeight = 0
      if (['ios', 'devtools'].includes(platform)) {
        navHeight = 44
      } else {
        navHeight = 48
      }
      return navHeight + statusBarHeight
    }
  },
  methods: {
    // 获取投诉类型字典
    async getComplainTypeList () {
      const { code, data, msg } = await getSystemDictTypeData('complain_type')
      if (code === 200) {
        this.complainTypeList.splice(0, 1, data)
      } else {
        this.$modal.msgError(msg)
      }
    },
    /**
     * 判断位置授权
     */
    isGetLocation () {
      uni.getSetting({
        success: (res) => {
          console.log('获取授权信息', res)
          if (!res.authSetting[scope]) {
            this.getAuthorize(scope)
          } else {
            this.getLocation()
          }
        },
        fail: (err) => {
          console.error(err)
        }
      })
    },
    /**
     * 获取位置授权
     */
    getAuthorize() {
      uni.authorize({
        scope,
        success: (res) => {
          console.log('授权成功', res)
          this.getLocation()
        }
      })
    },
    /**
     * 获取当前位置
     */
    getLocation () {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          if(res.errMsg === "getLocation:ok"){
            console.log('选择位置', res)
            this.latitude= res.latitude
            this.longitude = res.longitude
          }
        },
        error: (err) => {
          console.error('获取位置失败', err)
        }
      })
    },
    // 查看位置
    openMap () {
      uni.chooseLocation({
        latitude: this.latitude,
        longitude: this.longitude,
        success: (res) => {
          const { longitude, latitude, address } = res
          this.longitude = longitude
          this.latitude = latitude
          this.form.address = address
        },
        fail: (err) => {
          console.error('选择位置失败', err)
        }
      })
    },
    /**
     * 选择投诉类型
     * @param event
     */
    confirmComplainType (event) {
      this.form.complainType = event.value[0]
      this.showComplainType = false
      this.$refs.form.validateField('complainType')
    },
    addImage (event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      const lists = [].concat(event.file)
      const file = lists[0]
      this.form.imageList.splice(0, 1,{
        ...file,
        status: 'uploading',
        message: '上传中'
      })
      uploadImg({
        filePath: file.url
      }).then(res => {
        const url = res.data.url
        this.form.imageList.splice(0, 1,{
          ...file,
          status: 'success',
          message: '',
          url
        })
        this.$refs.form.validateField('imageList');
      })
    },
    deleteImage () {
      this.form.imageList.splice(0, 1)
      this.$refs.form.validateField('imageList')
    },
    /**
     * 下一步
     */
    next () {
      this.$refs.form.validate().then(res => {
        complainAdd({
          address: this.form.address,
          complainFor: this.form.complainFor,
          complainImg: this.form.imageList[0].url,
          complainName: this.form.complainName,
          complainPhone: this.form.complainPhone,
          complainReason: this.form.complainReason,
          type: this.form.complainType.dictValue
        }).then(({ code, msg }) => {
          if (code !== 200) {
            this.$modal.msgError(msg)
            return
          }
          this.$modal.msgSuccess('已投诉')
          uni.navigateBack()
        })
      }).catch(errors => {
        console.warn('errors', errors)
        this.$modal.msgError(errors[0].message)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.store_detail_page {
  width: 100vw;
  height: 100vh;
  background-color: #F3F3F3;
  .navBar {
    display: flex;
    align-items: center;
    .nav_title {
      font-size: 36rpx;
      font-weight: 400;
      color: #000000;
      margin-left: 8rpx;
    }
  }
  .content {
    padding: 0 16rpx;
    box-sizing: border-box;
    .card_list {
      padding-bottom: 184rpx;
    }
    .card_box {
      background-color: #fff;
      display: flex;
      flex-direction: column;
      border-radius: 16rpx;
      padding: 0 32rpx;
      margin-top: 16rpx;
      ::v-deep .u-textarea {
        padding: 0;
      }
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 144rpx;
    background: #FFFFFF;
    padding: 18rpx 24rpx 0;
    border: 1rpx solid #F3F3F3;
    z-index: 99;
  }
}
</style>
